package category

import (
	"context"
	"github.com/google/uuid"
	"github.com/kuangshp/go-utils/k"
	"github.com/spf13/cast"
	"insighttracking/common/utils"
	"insighttracking/query/dao"
	"insighttracking/query/model"
	"net/http"
	"strings"

	"insighttracking/apps/admin/internal/svc"
	"insighttracking/apps/admin/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
	"os"
)

type GetCategoryPageApiLogic struct {
	logx.Logger
	ctx     context.Context
	svcCtx  *svc.ServiceContext
	Request *http.Request
}

func NewGetCategoryPageApiLogic(ctx context.Context, svcCtx *svc.ServiceContext, request *http.Request) *GetCategoryPageApiLogic {
	hostname, _ := os.Hostname()
	return &GetCategoryPageApiLogic{
		Logger: logx.WithContext(ctx).WithCallerSkip(0).WithFields(
			logx.Field("Log_UUID", uuid.New().String()),
			logx.Field("hostname", hostname)),
		ctx:     ctx,
		svcCtx:  svcCtx,
		Request: request,
	}
}

func (l *GetCategoryPageApiLogic) GetCategoryPageApi(req *types.GetCategoryPageReq) (resp *types.CategoryPageResp, err error) {
	// todo: add your logic here and delete this line
	enterpriseId := cast.ToInt64(l.ctx.Value("enterpriseId"))
	offset, limit := utils.DbPage(req.PageNumber, req.PageSize)
	tx := dao.CategoryEntity.WithContext(l.ctx).Where(
		dao.CategoryEntity.EnterpriseID.Eq(enterpriseId),
	)
	if req.Name != "" {
		req.Name = strings.ReplaceAll(req.Name, "%", "\\%")
		req.Name = strings.ReplaceAll(req.Name, "_", "\\%")
		tx = tx.Where(dao.CategoryEntity.Name.Like("%" + req.Name + "%"))
	}
	if req.Status != "" {
		tx = tx.Where(dao.CategoryEntity.Status.Eq(cast.ToInt64(req.Status)))
	}
	if req.ParentID != "" {
		tx = tx.Where(dao.CategoryEntity.ParentID.Eq(cast.ToInt64(req.ParentID)))
	}
	categoryEntities, count, err := tx.Order(dao.CategoryEntity.Sort, dao.CategoryEntity.ID.Desc()).FindByPage(offset, limit)
	if err != nil {
		return &types.CategoryPageResp{
			Data: make([]types.CategoryModel, 0),
			PageBaseResp: types.PageBaseResp{
				Total:      count,
				PageSize:   req.PageSize,
				PageNumber: req.PageNumber,
			},
		}, nil
	}
	// 查找父节点
	parentIdList := k.Map(categoryEntities, func(item *model.CategoryEntity, index int) int64 {
		return item.ID
	})
	entities, _ := dao.CategoryEntity.WithContext(l.ctx).Where(dao.CategoryEntity.ParentID.In(parentIdList...)).Find()
	parentNameMap := make(map[int64]string)
	childrenGroup := make(map[int64][]*model.CategoryEntity)
	if len(entities) > 0 {
		parentNameMap = k.ToMap(entities, func(item *model.CategoryEntity) (int64, string) {
			return item.ParentID, item.Name
		})
		childrenGroup = k.GroupBy(entities, func(item *model.CategoryEntity) int64 {
			return item.ParentID
		})
	}
	// 查找是否有子节点
	categoryModels := k.Map(categoryEntities, func(item *model.CategoryEntity, index int) types.CategoryModel {
		return types.CategoryModel{
			ID:          item.ID,                                            // 主键id
			Name:        item.Name,                                          // 单位名称
			Sort:        item.Sort,                                          // 排序
			Status:      item.Status,                                        // 状态:1是正常,2是禁用
			Describe:    item.Describe,                                      // 描述
			ParentID:    item.ParentID,                                      // 父节点id
			ParentName:  parentNameMap[item.ParentID],                       // 父节点名称
			HasChildren: k.If(len(childrenGroup[item.ID]) > 0, true, false), // 是否有子节点
			CreatedAt:   utils.TimestampToString(item.CreatedAt),            // 创建时间
			UpdatedAt:   utils.TimestampToString(item.UpdatedAt),            // 更新时间
		}
	})
	return &types.CategoryPageResp{
		Data: categoryModels,
		PageBaseResp: types.PageBaseResp{
			Total:      count,
			PageSize:   req.PageSize,
			PageNumber: req.PageNumber,
		},
	}, nil
}
